﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sys.WebRes.Data;
using Sys.WebRes.Publish.Areas.Admin.Models;
using System.IO;

namespace Sys.WebRes.Publish.Areas.Admin.Controllers
{
    public partial class ResourceController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">资源类型ID</param>
        /// <returns></returns>
        public ActionResult List(int? id, int page = 1, int rows = 10)
        {
            using (var db = new ResourceSysEntities())
            {
                var query = db.ResourceTBL
                                .Where(p => p.DeletedFlag == false 
                                    && (id == null | id == 1 || p.ResType.ID == id));

                int count = query.Count();

                var list = query.Take(rows * page).OrderBy(p => p.UpdateDate)
                                .Skip((page - 1) * rows)
                                .Select(p=>new ResourceRowModel{
                                    ID = p.ID,
                                    Name = p.Name,
                                    ResTypeID = p.ResType.ID,
                                    StatusTypeID = p.StatusType.ID,
                                    SectionID = p.SecResLinks.FirstOrDefault().Section.ID,
                                    SectionName = p.SecResLinks.FirstOrDefault().Section.Name,
                                    GUID = p.GUID,
                                    FilePath = p.Thumbnail,
                                    CreatorID = p.Creator.ID,
                                    CreatorName = p.Creator.Name,
                                    CreateDate = p.CreateDate,
                                    UpdateDate = p.UpdateDate})
                                .ToList();


                return Json(new {total=count, rows=list}, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 获取资源
        /// </summary>
        /// <param name="id"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        private T GetResourceModel<T>(int id, ResourceSysEntities db)
            where T : ResourceModel, new()
        {
            var model = new T();
            var res = db.ResourceTBL
                        .Where(p => p.DeletedFlag == false && p.ID == id)
                        .Select(p => new
                        {
                            Target = p,
                            CreatorID = (int?)p.Creator.ID,
                            EditorID = (int?)p.Editor.ID,
                            ResTypeID = p.ResType.ID,
                            StatusTypeID = p.StatusType.ID,
                            CreateDate = (DateTime?)p.CreateDate,
                            UpdateDate = (DateTime?)p.UpdateDate,
                            ResCount = p.ResCount,
                            GlobalRes = p.GlobalRes,
                            SecLinks = p.SecResLinks
                                        .Select(s => new SecResLinkModel
                                        {
                                            SectionID = s.Section.ID,
                                            OrderNo = s.OrderNo,
                                            TopLevel = s.TopLevel
                                        }),
                            TagLinks = p.TagResLinks
                                        .Select(t => t.Tag.Name),

                            Attachments = p.ResAttachLinks
                                            .Select(a=>new ResAttachLinkModel
                                            {
                                                AttachmentID = a.Attachment.ID,
                                                Title = a.Title,
                                                Explain = a.Explain,
                                                OrderNo = a.OrderNo,
                                                Url = a.Url,
                                                ResAttachLinkTypeID = a.LinkType.ID
                                            })
                        })
                        .FirstOrDefault();

            res.Clone(model);

            res.Target.CopyTo(model);

            if (res.TagLinks != null)
            {
                model.Tags = string.Join(",", res.TagLinks.ToArray());
            }

            if (res.ResCount != null)
            {
                model.HasCount = true;
                res.ResCount.CopyTo(model.ResCount);
            }

            if (res.GlobalRes != null)
            {
                model.IsGlobal = true;
                res.GlobalRes.CopyTo(model.GlobalRes);
            }

            if (res.SecLinks != null)
            {
                model.Sections.AddRange(res.SecLinks);
                if (model.Sections.Count == 0)
                {
                    model.Sections.Add(new SecResLinkModel());
                }
            }
            if (res.Attachments != null)
            {
                model.Attachments.AddRange(res.Attachments);
                if (model.Attachments.Count == 0)
                {
                    model.Attachments.Add(new ResAttachLinkModel());
                }
            }

            return model;
        }

        /// <summary>
        /// 保存资源
        /// </summary>
        /// <param name="db"></param>
        /// <param name="id"></param>
        /// <param name="model"></param>
        private void SaveResource(ResourceSysEntities db, int? id, ResourceModel model)
        {
            model.Sections.RemoveAll(p => p.SectionID == 0);

            Resource res = null;
            if (id == null || id == 0)
            {
                res = new Resource();
                res.ID = (db.ResourceTBL.Max<Resource, int?>(p => p.ID) ?? 0) + 1;
                db.AddToResourceTBL(res);
                model.ID = res.ID;
            }
            else
            {
                res = DeleteResourceInfo(db, model.ID, false);
            }

            SetResourceBaseInfo(db, res, model);
            SetResourceLinkInfo(db, res, model);
        }

        /// <summary>
        /// 删除表数据
        /// </summary>
        /// <param name="db"></param>
        /// <param name="id"></param>
        /// <param name="includeResource"></param>
        /// <returns></returns>
        private Resource DeleteResourceInfo(ResourceSysEntities db, int id, bool includeResource)
        {
            var res = db.ResourceTBL.Where(p => p.DeletedFlag == false && p.ID == id)
                                    .Select(p => new
                                    {
                                        Target = p,
                                        ResCount = p.ResCount,
                                        GlobalRes = p.GlobalRes,
                                        SecResLinks = p.SecResLinks,
                                        TagResLinks = p.TagResLinks,
                                        AttachLinks = p.ResAttachLinks
                                    })
                                    .FirstOrDefault();

            if (res == null)
            {
                throw new RecordNotFoundException(id, typeof(Resource));
            }

            if (res.ResCount != null)
            {
                db.DeleteObject(res.ResCount);
            }

            if (res.GlobalRes != null)
            {
                db.DeleteObject(res.GlobalRes);
            }

            //删除关联栏目信息
            res.SecResLinks.ToList().ForEach(p =>
            {
                db.DeleteObject(p);
            });
            //删除关联标签信息
            res.TagResLinks.ToList().ForEach(p =>
            {
                db.DeleteObject(p);
            });
            //删除附件关联
            res.AttachLinks.ToList().ForEach(p =>
            {
                db.DeleteObject(p);
            });

            if (includeResource == true)
            {
                db.DeleteObject(res);
            }

            return res.Target;
        }

        /// <summary>
        /// 设置基本属性
        /// </summary>
        /// <param name="db"></param>
        /// <param name="res"></param>
        /// <param name="model"></param>
        private void SetResourceBaseInfo(ResourceSysEntities db, Resource res, ResourceModel model)
        {
            res.CopyFrom(model);
            if (model.CreatorID == null || model.CreatorID == 0)
            {
                model.CreatorID = this.LoginUser.ID;
            }
            if (model.CreateDate == null)
            {
                model.CreateDate = db.Now;
            }

            res.ResType = db.ResTypeTBL.FirstOrDefault(p => p.ID == model.ResTypeID);
            res.Language = db.LanguageTBL.FirstOrDefault(p => p.ID == 1);
            res.StatusType = db.ResStatusTypeTBL.FirstOrDefault(p => p.ID == model.StatusTypeID);
            res.Creator = db.UserTBL.FirstOrDefault(p => p.ID == model.CreatorID);
            res.Editor = db.UserTBL.FirstOrDefault(p => p.ID == model.EditorID);
            res.MadeDate = model.MadeDate;
            res.CreateDate = model.CreateDate ?? db.Now;
            res.UpdateDate = model.UpdateDate;
        }

        /// <summary>
        /// 修改关联表
        /// </summary>
        /// <param name="db"></param>
        /// <param name="res"></param>
        /// <param name="model"></param>
        private void SetResourceLinkInfo(ResourceSysEntities db, Resource res, ResourceModel model)
        {
            if (model.HasCount)
            {
                var count = new ResCount()
                {
                    ResourceID = res.ID,
                    Resource = res
                };
                count.CopyFrom(model.ResCount);
                res.ResCount = count;
            }
            if (model.IsGlobal)
            {
                var glb = new GlobalRes()
                {
                    ResourceID = res.ID,
                    Resource = res
                };
                glb.CopyFrom(model.GlobalRes);
                res.GlobalRes = glb;
            }

            AddSecResLink(db, res, model);

            AddTagResLink(db, res, model);

            AddResAttachLink(db, res, model);
        }

        /// <summary>
        /// 添加栏目信息
        /// </summary>
        /// <param name="db"></param>
        /// <param name="model"></param>
        /// <param name="res"></param>
        private void AddSecResLink(ResourceSysEntities db, Resource res, ResourceModel model)
        {
            foreach (var sec in model.Sections)
            {
                if (sec.SectionID > 0)
                {
                    var secLink = new SecResLink()
                    {
                        Resource = res,
                        OrderNo = sec.OrderNo,
                        TopLevel = sec.TopLevel,
                        Section = db.SectionTBL.FirstOrDefault(p => p.ID == sec.SectionID)
                    };

                    db.AddToSecResLinkTBL(secLink);
                }
            }
        }

        /// <summary>
        /// 添加标签信息
        /// </summary>
        /// <param name="db"></param>
        /// <param name="res"></param>
        /// <param name="model"></param>
        private void AddTagResLink(ResourceSysEntities db, Resource res, ResourceModel model)
        {
            if (string.IsNullOrEmpty(model.Tags))
            {
                return;
            }

            string[] tagNames = model.Tags.Split(',');
            var id = db.TagTBL.Max<Tag, int?>(p => p.ID) ?? 0;
            foreach (var tagName in tagNames)
            {
                var tag = db.TagTBL.FirstOrDefault(p => p.Name == tagName);
                if (tag == null)
                {
                    tag = new Tag()
                    {
                        ID = ++id,
                        Name = tagName,
                        CreateDate = DateTime.Now,
                        Abbr = tagName,
                        DeletedFlag = false
                    };
                    db.AddToTagTBL(tag);
                }
                db.AddToTagResLinkTBL(new TagResLink() { ResourceID = res.ID, TagID = tag.ID, Tag = tag, Resource = res });
            }
        }

        /// <summary>
        /// 添加附件关联
        /// </summary>
        /// <param name="db"></param>
        /// <param name="res"></param>
        /// <param name="model"></param>
        private void AddResAttachLink(ResourceSysEntities db, Resource res, ResourceModel model)
        {
            if (model.Attachments == null || model.Attachments.Count == 0)
            {
                return;
            }

            foreach (var attach in model.Attachments)
            {
                if (attach.AttachmentID > 0)
                {
                    var attachLink = new ResAttachLink()
                    {
                        Resource = res,
                        OrderNo = attach.OrderNo,
                        Title = attach.Title,
                        Explain = attach.Explain,
                        Url = attach.Url,
                        LinkType = db.ResAttachLinkTypeTBL.FirstOrDefault(p => p.ID == attach.ResAttachLinkTypeID),
                        Attachment = attach.Attachment??db.AttachmentTBL.FirstOrDefault(p => p.ID == attach.AttachmentID)
                    };

                    db.AddToResAttachLinkTBL(attachLink);
                }
            }
        }
    }
}
